package com.nightsoul.shirotest.web.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

public class AnyRoleFilter extends AccessControlFilter {
	private String unauthorizedUrl = "/unauthorized.jsp";
    private String loginUrl = "/login.jsp";

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		String[] roles = (String[]) mappedValue;
		if(roles == null) {
			return true;//如果没有设置角色参数，默认成功
		}
		for(String role : roles) {
			if(getSubject(request, response).hasRole(role)) {
				return true;
			}
		}
		return false;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		Subject subject = super.getSubject(request, response);
		if(subject.getPrincipal() == null) {//表示没有登录，重定向到登录页面
			super.saveRequest(request);
			WebUtils.issueRedirect(request, response, loginUrl);
		} else {
			if(StringUtils.hasText(unauthorizedUrl)) {
				WebUtils.issueRedirect(request, response, unauthorizedUrl);
			} else {
				WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
			}
		}
		return false;
	}

	public String getUnauthorizedUrl() {
		return unauthorizedUrl;
	}

	public void setUnauthorizedUrl(String unauthorizedUrl) {
		this.unauthorizedUrl = unauthorizedUrl;
	}

	public String getLoginUrl() {
		return loginUrl;
	}

	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}


}
